//
//  RegisteredViewController.m
//  tuanGG
//
//  Created by 微他 on 15/9/25.
//  Copyright (c) 2015年 weita. All rights reserved.
//

#import "RegisteredViewController.h"
#import "Header.h"
#import "ValidateMobileWithEmail.h"
#import "CustomAlertView.h"
#import "RegisterSaveViewController.h"
@interface RegisteredViewController ()<UIAlertViewDelegate,UITextFieldDelegate>
{
UIView * _backView;
UIView * _leftView1;
UIView * _pswleftView;
UIView * _authleftView;
UIView * _inviteView;
}
@property (nonatomic,strong)UIButton * authCodeBtn;
@property (nonatomic,strong)UIButton * nextBtn;
@end

@implementation RegisteredViewController
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self addnavigationTitle:@"注册" navColor:@"4fd2be"];
    self.view.backgroundColor=UIColorFromRGB(base_gary_bg);
    [self lqkinRegisterInit];
    // Do any additional setup after loading the view.
    [self initNav];
}
- (void)initNav {
    self.navigationController.navigationBar.frame = CGRectMake(0, -64, ScreenWidth, 64);
    UIView *nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, self.navigationController.navigationBar.frame.size.height)];
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, nav.frame.size.height-35, 30, 30)];
    [backButton setImage:IMGNAME(@"back") forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    nav.backgroundColor = [UIColor colorWithHexString:@"4fd2be"];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, nav.frame.size.height-30, ScreenWidth, 20)];
    label.text = @"注册";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:font_Font size:20];
    label.textAlignment = NSTextAlignmentCenter;
    [nav addSubview:label];
    [nav addSubview:backButton];
    [self.view addSubview:nav];
}
- (void)backButton {
    NSLog(@"退出");
    if (_index == 10) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if(_index == 11){
    [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)lqkinRegisterInit
{
    _backView = [[UIView alloc]initWithFrame:CGRectMake(15, 15+64, ScreenWidth - 30, 185)];
    [_backView.layer setCornerRadius:5.0];
    _backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_backView];
    
    //账号
    _phoneNum = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_backView.bounds), 45)];
    _phoneNum.placeholder = @"请输入手机号";
    _phoneNum.font =BOLD_FONT(12);
    _phoneNum.keyboardType = UIKeyboardTypeNumberPad;
    _phoneNum.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_backView addSubview:_phoneNum];
    
    _leftView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 45)];
    
    UIImageView * phoneleft = [[UIImageView alloc]initWithFrame:CGRectMake(10, 13, 17, 18)];
    phoneleft.image = [UIImage imageNamed:@"AcountLeftimage.png"];
    [_leftView1 addSubview:phoneleft];
    _phoneNum.leftView = _leftView1;
    _phoneNum.leftViewMode = UITextFieldViewModeAlways;
    
    //密码
    _password = [[UITextField alloc]initWithFrame:CGRectMake(0, 45, CGRectGetWidth(_backView.bounds), 45)];
    _password.placeholder = @"请输入密码";
    _password.font = BOLD_FONT(12);
    [_backView addSubview:_password];
    
    _pswleftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 45)];
    
    UIImageView * passwordleft = [[UIImageView alloc]initWithFrame:CGRectMake(10, 13, 17, 18)];
    passwordleft.image = [UIImage imageNamed:@"authCodeLeftimage.png"];
    [_pswleftView addSubview:passwordleft];
    _password.leftView = _pswleftView;
    _password.secureTextEntry = YES;
    _password.delegate = self;
    _password.leftViewMode = UITextFieldViewModeAlways;
    
    //验证码
    _authCode = [[UITextField alloc]initWithFrame:CGRectMake(0, 90, CGRectGetWidth(_backView.bounds), 45)];
    _authCode.placeholder = @"请输入验证码";
    _authCode.font = BOLD_FONT(12);
    [_backView addSubview:_authCode];
    
    _authleftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 45)];
    
    UIImageView * authleft = [[UIImageView alloc]initWithFrame:CGRectMake(10, 13, 17, 18)];
    authleft.image = [UIImage imageNamed:@"authCodeLeftimage.png"];
    [_authleftView addSubview:authleft];
    _authCode.leftView = _authleftView;
    _authCode.leftViewMode = UITextFieldViewModeAlways;
    
    for (int i = 1; i < 4; i ++) {
        //分割线
        UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 45* i, ScreenWidth-30, 1)];
        lineView.backgroundColor = [UIColor colorWithHexString:@"c8c8c8"alpha:0.5];
        [_backView addSubview:lineView];
    }
    
    //验证码
    _authCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _authCodeBtn.frame = CGRectMake(CGRectGetMaxX(self.authCode.bounds)-70, 7.5, 60, 30);
    _authCodeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _authCodeBtn.titleLabel.numberOfLines = 2;
    [_authCodeBtn setBackgroundImage:[UIImage imageNamed:@"authCodeBtnImage.png"] forState:UIControlStateNormal];
    [_authCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_authCodeBtn setTitleColor:[UIColor colorWithHexString:@"33ccbf"] forState:UIControlStateNormal];
    [_authCodeBtn addTarget:self action:@selector(processbtnAuthClick:) forControlEvents:UIControlEventTouchUpInside];
    _authCodeBtn.tag = 110;
    _authCodeBtn.layer.cornerRadius = 5;
    _authCodeBtn.layer.borderWidth = 1;
    _authCodeBtn.layer.borderColor = [[UIColor colorWithHexString:@"33ccbf"]CGColor];
    _authCodeBtn.titleLabel.font = BOLD_FONT(11);
    [self.authCode addSubview:_authCodeBtn];
    _inviteView= [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 45)];
    UIImageView *inviteImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, 13, 17, 20)];
    [inviteImage sd_setImageWithURL:nil placeholderImage:IMGNAME(@"邀请码(商家版)")];
    [_inviteView addSubview:inviteImage];
    _Invite = [[UITextField alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(_authCode.frame)+1 , CGRectGetWidth(_password.frame), 45)];
    _Invite.backgroundColor = [UIColor whiteColor];
    _Invite.placeholder = @"请输入邀请码";
    _Invite.leftView = _inviteView;
    _Invite.leftViewMode = UITextFieldViewModeAlways;
    _Invite.font = BOLD_FONT(12);
    [_backView addSubview:_Invite];
    //下一步
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextBtn.frame = CGRectMake(15, CGRectGetHeight(_backView.bounds) + 56 +15+64, ScreenWidth - 30, 40);
    [_nextBtn.layer setCornerRadius:5.0];
    [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    _nextBtn.titleLabel.font = BOLD_FONT(15);
    [_nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_nextBtn setBackgroundColor:[UIColor colorWithHexString:@"33ccbf"]];
    [_nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextBtn];
    
}

//获取验证码
- (void)processbtnAuthClick:(UIButton *)sender
{
    if ([_phoneNum.text isEqualToString:@""]) {
        [Common addAlert:@"请输入您的手机号码"];
        
    }
    else
    {
        if (![ValidateMobileWithEmail validateMobile:_phoneNum.text]) {
            [Common addAlert:@"手机号码格式不正确"];
        }
        else
        {
            [CustomAlertView alterMsg:[NSString stringWithFormat:@"是否是通过%@号码获取验证码吗?",self.phoneNum.text] delegate:self];
        }
        
    }
    
}

#pragma amrk - <UIAlertViewDelegate>
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSLog(@"sssssss");
        //获取验证码
        [Common verificationCode:^{
            [_authCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            _authCodeBtn.userInteractionEnabled = YES;
        } blockNo:^(id time) {
            [_authCodeBtn setTitle:[NSString stringWithFormat:@"获取验证码\n     %@'s",time] forState:UIControlStateNormal];
            NSLog(@"%@",_authCodeBtn.titleLabel.text);
            _authCodeBtn.userInteractionEnabled = NO;
            //发送验证
        }];
        
        //发送验证信息
//        [SMS_SDK getVerificationCodeBySMSWithPhone:self.phoneNum.text zone:@"86"   result:^(SMS_SDKError *error) {
//            
//            if (!error) {
//
//            }
//            else
//            {   if (!error.description) {
//                  NSLog(@"错误:%@",error.description);
//                [Common addAlert:@"发送失败"];
//                }
//                [CustomAlertView alterSureMsg:[NSString stringWithFormat:@"%@",error.description] delegate:nil];
//            }
//            
//        }];
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.phoneNum.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
            if (!error) {
                [Common addAlert:@"发送成功"];
            }else{
                [Common addAlert:@"发送失败"];
            }

        }];

    }
}

- (void)registerNetWokring
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:_phoneNum.text forKey:@"tel"];//手机号码
    [params setObject:_password.text forKey:@"psw"];//密码
    [params setObject:_authCode.text forKey:@"vcode"];//验证码
    [params setObject:_Invite.text forKey:@"invitecode"];//邀请码
//    [params setObject:@"1" forKey:@"mode"];

//    [GLAFRequest startRequest:[NSString stringWithFormat:@"%@%@",baseurl_url,codechecked_url] paramsDic:params defaultdialog:YES ispost:YES handleSuccess:^(id sta, NSDictionary *paramsDic) {
//        NSLog(@"数据:%@",sta);

//    } doFinally:^(NSDictionary *paramsDic) {
//
//    }];
//    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]init];
//    [manager POST:[NSString stringWithFormat:@"%@%@",baseurl_url,codechecked_url] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"请求数据：%@",responseObject);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"错误信息：%@",error.localizedDescription);
//    }];
    [GLAFRequest startRequest:[NSString stringWithFormat:@"%@%@",baseurl_url,codechecked_url] paramsDic:params handleSuccess:^(id sta, NSDictionary *paramsDic) {
               NSLog(@"%@",sta);
        //       NSLog(@"%@",sta[@"msg"]);
        if ([sta[@"code"] integerValue] ==1) {

            RegisterSaveViewController * regSave = [[RegisterSaveViewController alloc]initWithinforPhone:self.phoneNum.text psw:self.password.text authcode:self.authCode.text];
            [self.navigationController pushViewController:regSave animated:YES];

        }
        
    } netWorkFail:^(NSDictionary *paramsDic) {
        NSLog(@"%@",paramsDic);
        //       NSLog(@"失败");
        [CustomAlertView alterSureMsg:@"网络连接异常,请检查网络连接" delegate:nil];
    }];

}
//下一页
- (void)nextBtnClick:(UIButton *)sender
{
    [self decideTxtIsNull];

//        RegisterSaveViewController * regSave = [[RegisterSaveViewController alloc]init];
//        [self.navigationController pushViewController:regSave animated:YES];
}

//判断字段
- (void)decideTxtIsNull
{
    if ([_phoneNum.text isEqualToString:@""]) {
        
        [CustomAlertView alterSureMsg:@"请输入手机号码" delegate:nil];
    }
    else
    {
        if ([_password.text isEqualToString:@""]) {
            [CustomAlertView alterSureMsg:@"请输入密码" delegate:nil];
        }
        else
        {
            if (_password.text.length < 6) {
                [CustomAlertView alterMsg:@"密码必须设置为6-16位" delegate:nil];
            }
            else
            {
                if (_authCode.text.length != 4) {
                    [CustomAlertView alterSureMsg:@"请输入4位数的验证码" delegate:nil];
                }
                else
                {
                    if (_Invite.text.length != 10) {
                        [CustomAlertView alterMsg:@"请输入邀请码" delegate:nil];
                    }else
                        [self registerNetWokring];
                    
                }
            }
            
        }
    }
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}
@end
